package com.tnovoselec.server.travelassistant.worker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.TimerTask;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class RefreshCache extends TimerTask {

	IParser gpp;
	IParser erp;
	IParser wp;

	public RefreshCache() {
		gpp = new GasPricesParser();
		erp = new ExchangeRatesParser();
		wp = new WeatherParser();

	}

	@Override
	public void run() {

		gpp.parse();
		erp.parse();
		wp.parse();

		saveFile(wp.getDoc(), wp.getXMLName());
		saveFile(gpp.getDoc(), gpp.getXMLName());
		saveFile(erp.getDoc(), erp.getXMLName());
	}

	private void saveFile(Document doc, String fileName) {
		System.out.println(fileName);
		if (doc == null || fileName == null) {
			return;
		}

		try {
			File f = new File("/usr/local/TravelAssistant/server/war/xmls/" + fileName);
			FileWriter fw = new FileWriter(f);
			DOMSource domSource = new DOMSource(doc);
			StringWriter writer = new StringWriter();
			StreamResult result = new StreamResult(writer);
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			transformer.transform(domSource, result);
			String content = new String(writer.toString().getBytes(), "UTF-8");
			fw.write(content);
			fw.flush();
			fw.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
